/*
*******************************************************************************
* 用户接口常规工具集(需要Hongs-CORE-js的支持)
*
* Author: Huang Hong
* Support: kevin.hongs@gmail.com, +8613718308220
*******************************************************************************
*/

/** 列表构造器 **/

function HsListMaker(listDiv) {
  var _this = this;

  if (typeof listDiv == "string") {
    _this.listDiv = hsId(listDiv);
  }
  else {
    _this.listDiv = listDiv;
  }

  _this.fields = {};
  _this.params = {};

  _this.LA = new HsListAction();
  _this.LA.useLE = true;
  _this.LA.useFW = true;

  _this.LA.onBack = function() {
    if (_this.onBack()) {
      return true;
    }

    if (_this.LA.actionType == "add") {
//      _this.setParams({sort:'mtime', desc:'1', page:'1'});
    }
    else if (_this.LA.actionType == "set") {
      if (_this.params["sort"] == "mtime") {
        _this.setParams({desc:'1', page:'1'});
      }
    }
    else if (_this.LA.actionType == "del") {
      if (_this.params["sort"] == "mtime") {
        _this.setParams({desc:'1', page:'1'});
      }
    }

    _this.loadList();
    return true;
  };

  _this.setAttributes = function(attrib) {
    _this.loadAction    = attrib.loadAction   ? attrib.loadAction : "";
    _this.LA.getAction  = attrib.getAction    ? attrib.getAction  : "";
    _this.LA.setAction  = attrib.setAction    ? attrib.setAction  : "";
    _this.LA.delAction  = attrib.delAction    ? attrib.delAction  : "";

    _this.LA.idVar      = attrib.idVar        ? attrib.idVar      : "id";
    _this.LA.idsVar     = attrib.idsVar       ? attrib.idsVar     : "ids[]";

    _this.withCheckbox  = attrib.withCheckbox ? true              : false;

    _this.LA.stateVar       = attrib.stateVar          ? attrib.stateVar     : "state";
    _this.LA.publicVar     = attrib.publicVar         ? attrib.publicVar    : "is_public";  
    _this.stopVar        = attrib.stopVar          ? attrib.stopVar     : "1";  
    _this.startVar        = attrib.startVar          ? attrib.startVar     : "0";
    _this.stopAction        = attrib.stopAction        ? attrib.stopAction   : "";
    _this.withStopButton    = attrib.withStopButton    ? true                : false;
    _this.withDelAllButton  = attrib.withDelAllButton  ? true                : false;
    _this.stopBackFunc      = attrib.stopBackFunc      ? attrib.stopBackFunc : "";
    //每页显示条数
    _this.rowNums           = attrib.rowNums           ? attrib.rowNums      :['10','20','50','100'];

    if (attrib.withFuncBtns) {
      var s = attrib.withFuncBtns.replace(/ /g, "");
      if (s === "all") {
        _this.withFuncBtns = {"get":true,"set":true,"del":true,"stop":true};
      }
      else {
        var a = s.split(",");
        _this.withFuncBtns = {};
        for (var i = 0; i < a.length; i ++) {
          switch (a[i]) {
            case "get": _this.withFuncBtns["get"] = true; break;
            case "set": _this.withFuncBtns["set"] = true; break;
            case "del": _this.withFuncBtns["del"] = true; break;
            case "stop": _this.withFuncBtns["stop"] = true; break;
          }
        }
      }
    }
    else {
      _this.withFuncBtns = false;
    }
  };

  _this.setFields = function(fields) {
    _this.fields = {};

    if (!fields._check && _this.withCheckbox) {
      _this.fields._check = {};
    }

    for (var field in fields) {
      _this.fields[field] = fields[field];
    }

    if (!fields._funcs && _this.withFuncBtns) {
      _this.fields._funcs = {};
    }

    if (_this.withCheckbox) {
      if (!_this.fields._check.htmlFunc) {
        _this.fields._check.htmlFunc = _this.makeCheck;
      }
      if (!_this.fields._check.className) {
        _this.fields._check.className = "list_check";
      }
    }

    if (_this.withFuncBtns) {
      if (!_this.fields._funcs.htmlFunc) {
        _this.fields._funcs.htmlFunc = _this.makeFuncs;
      }
      if (!_this.fields._funcs.className) {
        _this.fields._funcs.className = "list_funcs";
      }
      if (!_this.fields._funcs.text && !_this.fields._funcs.html) {
        _this.fields._funcs.text = "操作";
      }
    }
  };

  _this.setRowsNums = function(params) {
    _this.rowNums = {};
    for (var num in params) {
      _this.rowNums[num] = params[num];
    }
  };

  _this.setParams = function(params) {
    if (typeof params.length != "number") {
      for (var k in params) {
        if (params[k]) {
          _this.params[k] = params[k];
        }
        else {
          delete _this.params[k];
        }
      }
    }
    else {
      for (var i = 0; i < params.length; i ++) {
        // Is Radio or CheckBox
        if (params[i].tagName && params[i].tagName == "INPUT"
        && (params[i].type == "radio" || params[i].type == "checkbox")
         && params[i].checked == false) {
          continue;
        }

        // Is Select(仅单选)
        if (params[i].tagName && params[i].tagName == "SELECT") {
            var tempOption = hsGetSelectedOption(params[i]) ;
            if(tempOption != null){
                params[i].value = tempOption.value;
            } else {
                params[i].value = null ;
            }
        }

        if (params[i].value) {
          _this.params[params[i].name] = params[i].value;
        }
        else {
          delete _this.params[params[i].name];
        }
      }
    }
  };

  _this.loadList = function(params) {
    if (params) {
      _this.setParams(params);
    }

    _this.listError("数据加载中...", true);

    var url = _this.loadAction;
    if (_this.params) {
      url = hsUrlBindParams(url, _this.params);
    }
    // 加载数据
    var rsp = hsAjaxRequestGet(url);
    var rst = hsAjaxRequestResult(rsp, 3);

    // 加载失败
    if (rst == null) {
      _this.listError("加载列表失败");
      return;
    }
    if (!rst.__result) {
      if (!rst.__message) {
        _this.listError("加载列表失败");
      }
      else {
        _this.listError(rst.__message);
      }
      return;
    }

    //location访问后没有错误时调用
    if(_this.preLoadList){
        _this.preLoadList(rst) ;
    }

    // 加载错误
    if (rst.pager && rst.pager.errno) {
      rst.errno = rst.pager.errno;
    }
    if (rst.errno) {
      if (rst.error) {
        _this.listError(rst.error);
      }
      else if (rst.errno == 1) {
        _this.listError("当前列表为空");
      }
      else if (rst.errno == 2) {
        _this.loadList({"page":"-1"});
      }
      _this.onFail(rst);
      return;
    }

    // 清空内容区
    _this.listDiv.innerHTML = "";
    // 建立列表及分页
    if (rst.list) {
      _this.makeList(rst.list);
    }
    if (rst.pager) {
      _this.makePager(rst.pager);
    }
    _this.onLoad(rst);
  };

  _this.makeList = function(list) {
    var ta = document.createElement("table");
    var tb = document.createElement("tbody");
    var tr = document.createElement("tr");
    var th = document.createElement("th");
    var td = document.createElement("td");

    ta.setAttribute("cellpadding", 0);
    ta.setAttribute("cellspacing", 0);
    ta.className = "items";

    /** 处理表头 **/

    var headTr = tr.cloneNode(true);

    for (var field in _this.fields) {
      var headTh = th.cloneNode(true);
      var conf = _this.fields[field];

      // 全选复选框
      if (field == "_check") {
        var ck = document.createElement("input");
        ck.type = "checkbox";
        ck.onclick = _this.checkAll;
        headTh.appendChild(ck);
      }

    switch(conf.format){
        case 'int':
        if(text == null){
            text = '0';
        }
        else{
            text = _this.numberFormat(text);
        }
        headTh.style.textAlign = 'right';
        break;
    }
     if (conf.text) {
        headTh.appendChild(document.createTextNode(conf.text));
      }
      else if (conf.html) {
        headTh.innerHTML += conf.html;
      }
      else if (field != "_check") {
        headTh.innerHTML += "&nbsp;";
      }

      if (conf.className) {
        headTh.className = conf.className;
      }

      if (conf.align) {
        headTh.style.textAlign = conf.align;
      }

      if (conf.width) {
        headTh.style.width = conf.width + "px";
      }
      //2012-09-27 YQC+ 加入title
      if(conf.title){
          headTh.title = conf.title ;
      }

      if (conf.sortable) {
        var al = document.createElement("a");
        al.setAttribute("href", "javascript:void(0);");
        al.appendChild(headTh.firstChild);
        headTh.appendChild(al);

        var at = al.firstChild.nodeValue;
        if (_this.params.sort != field) {
          al.setAttribute("sort", field);
          al.setAttribute("desc", "0");
          //al.title = "点此按 "+at+" 排序";
        }
        else if (_this.params.desc != "1") {
          al.setAttribute("sort", field);
          al.setAttribute("desc", "1");
          //al.title = "点此按 "+at+" 逆向排序";
          al.appendChild(document.createTextNode("↓"));
        }
        else {
          al.setAttribute("sort", "");
          al.setAttribute("desc", "");
          //al.title = "点此取消对 "+at+" 的排序";
          al.appendChild(document.createTextNode("↑"));
        }

        new HsEventListener(al, "click", _this.sortBy);
      }

      //总量
      if (typeof(conf.sum) != "undefined") {
        var p = document.createElement("p");
        p.setAttribute("title", _this.numberFormat(conf.sum));
        p.innerHTML = _this.numberFormat(conf.sum);
        headTh.appendChild(p);
      }
      headTr.appendChild(headTh);
    }
    tb.appendChild(headTr);

    /** 处理表内容区 **/

    if (typeof list.length != "number") {
      list = hsObjectValues(list);
    }

    for (var i = 0; i < list.length; i ++) {
      var bodyTr = tr.cloneNode(true);

      _this.tr = bodyTr;     // 当前行对象
      _this.info = list[i];  // 当前行数据
      _this.index = i + 1;   // 当前行序号

      for (var field in _this.fields) {
        var bodyTd = td.cloneNode(true);
        var conf = _this.fields[field];

        _this.td = bodyTd;   // 当前列对象
        _this.field = field; // 当前列名称

        var text = _this.getArrValue(list[i], field);
        var html = null;

        switch(conf.format){
            case 'int':
            if(text == null){
                text = '0';
            }
            else{
                text = _this.numberFormat(text);
            }
            bodyTd.style.textAlign = 'right';
            break;
        }

        // afa扩展 创建时间 转换
        if ((field == "created" || field == "updated") && text.length == 10) {
          var time = parseInt(text);
          var date = new Date();
          date.setTime(time * 1000);
          var month = date.getMonth()+1;
          var day = date.getDate();
          var hour = date.getHours();
          var minutes = date.getMinutes();
          var seconds = date.getSeconds();
          if ((date.getMonth()+1) < 10) {
            month = "0"+(date.getMonth()+1);
          }
          if (date.getDate() < 10) {
            day = "0"+date.getDate();
          }
          if (date.getHours() < 10 ) {
            hour = "0" + date.getHours();
          }
          if (date.getMinutes() < 10) {
            minutes = "0" + date.getMinutes();
          }
          if (date.getSeconds() < 10) {
            var seconds = "0" + date.getSeconds();
          }
          text = date.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds;
        }
        else if (conf.textFunc) {
          text = conf.textFunc(text, _this);
          html = "";
        }
        else if (conf.htmlFunc) {
          html = conf.htmlFunc(text, _this);
          text = "";
        }

        
        if (text) {
        	//alert(text)
        	//alert(field);
          //判断是否为广告位时段报表   然后为维度追加a标签和onclick事件
         if(field == 'mdaPlaceTime'){
        	  var mdaPlaceTime = document.createElement('a');//添加a标签
        	  var textA = document.createTextNode(text);
        	  mdaPlaceTime.appendChild(textA);//追加显示字段
        	  mdaPlaceTime.href = "#";
        	  mdaPlaceTime.setAttribute('id',list[i].id) ;
//        	  mdaPlaceTime.onclick = show;//添加show方法，页面要写show()方法的实现
        	  mdaPlaceTime.onclick = function() { show(this.id); }//添加show方法，页面要写show()方法的实现
        	  
        	  bodyTd.appendChild(mdaPlaceTime);
        	  
         }else if(field == 'mdaPlaceFrom'){
        	//判断是否为广告位来源报表   然后为维度追加a标签和onclick事件
        	  var mdaPlaceFrom = document.createElement('a');//添加a标签
        	  var textA = document.createTextNode(text);
        	  mdaPlaceFrom.appendChild(textA);//追加显示字段
        	  mdaPlaceFrom.href = "#";
        	  mdaPlaceFrom.setAttribute('id',list[i].id) ;
//        	  mdaPlaceTime.onclick = show;//添加show方法，页面要写show()方法的实现
        	  mdaPlaceFrom.onclick = function() { show(this.id); }//添加show方法，页面要写show()方法的实现
        	  
        	  bodyTd.appendChild(mdaPlaceFrom);
        	  
          }else if(field == 'URL'){
        	//判断是否为广告位来源报表   然后为维度追加a标签和onclick事件
        	  var URL = document.createElement('a');//添加a标签
        	  var textA = document.createTextNode(text);
        	  URL.appendChild(textA);//追加显示字段
        	  URL.href = list[i].URL;
        	  URL.setAttribute('target','_blank') ;
//        	  mdaPlaceTime.onclick = show;//添加show方法，页面要写show()方法的实现
        	 // URL.onclick = function() { show(this.id); }//添加show方法，页面要写show()方法的实现
        	  
        	  bodyTd.appendChild(URL);
        	  
        	  //alert(";;;;;;");
          }else{
        	  bodyTd.appendChild(document.createTextNode(text));
          }
          
        }
        else if (html) {
          bodyTd.innerHTML += html;
        }
        else if (field != "_check" && field != "_funcs") {
          bodyTd.innerHTML += "&nbsp;";
        }

        if (conf.className) {
          bodyTd.className = conf.className;
        }

        if (conf.align) {
          bodyTd.style.textAlign = conf.align;
        }

        if (conf.width) {
          bodyTd.style.width = conf.width + "px";
        }

        bodyTr.appendChild(bodyTd);
      }

      tb.appendChild(bodyTr);
    }

    /** 处理列表后续问题 **/

    ta.appendChild(tb);
    _this.listDiv.appendChild(ta);

    _this.LA.listObj = ta;
    _this.LA.init();
  };

  _this.numberFormat = function(str) {
    var string = "";
    var intNum = 0;
    str = str.toString();
    for (var i = str.length - 1; i >= 0; i--) {
        if (str.charAt(i) == "." || str.charAt(i) == "-") {
            intNum = -1;
        }
        if (intNum >= 3) {
            string = "," + string;
            intNum = 0;
            i++;
        } else {
            string = str.charAt(i) + string;
            intNum++;
        }
    }
    return string != null?string:'0';
  }
  _this.makePager = function(pager) {
    var div = document.createElement("div");
    div.className = "pager";

    var page = hsParseInt(pager.page);
    var rows = hsParseInt(pager.rows);
    var rowsNum = hsParseInt(pager.rowsNum);
    var totalNum = hsParseInt(pager.totalNum);
    var totalPages = hsParseInt(pager.totalPages);

    var num1 = rows * (page - 1) + 1;
    var num2 = rowsNum + num1 - 1;

    if(_this.withDelAllButton){
      var aDelAll = document.createElement("a");
      aDelAll.className = "gridBtn fl";
      aDelAll.innerHTML = "批量删除";
      div.appendChild(aDelAll);
      new HsEventListener(aDelAll, "click", function(){_this.LA.del()});
    }
    
    if(_this.withStopButton){
      var startAll = document.createElement("a");
      startAll.className = "gridBtn fl";
      startAll.innerHTML = "启用";
      div.appendChild(startAll);
      new HsEventListener(startAll, "click", function(){_this.start()});
      
      var stopAll = document.createElement("a");
      stopAll.className = "gridBtn fl";
      stopAll.innerHTML = "停用";
      div.appendChild(stopAll);
      new HsEventListener(stopAll, "click", function(){_this.stop()});
    }
    

    if(_this.rowNums){
        // 每页 显示 条数 选择   李宣滨 start
        var s1 = document.createElement("span");
        s1.innerHTML = "每页显示 ";
        div.appendChild(s1);
        var sel = document.createElement("select");
        var i = 0;
        for (var num in _this.rowNums) {
          num = _this.rowNums[num]
          sel.options.add(new Option(num, num));
          if (num == rows) {
            sel.options[i].selected = true;
          }
          i++;
        }
        new HsEventListener(sel, "change", _this.gotoRowNum);
        div.appendChild(sel);

        var s1 = document.createElement("span");
        s1.innerHTML = " 条";
        div.appendChild(s1);
        if(totalPages <= 1 && totalNum < 10){
            var height = '365px';
        }else{
            var height = Number(_this.listDiv.firstChild.offsetHeight) + 42 + 'px';
        }
        _this.listDiv.style.height = height;
    }
    // 分页信息
    var s2 = document.createElement("span");
    s2.style.paddingLeft = "15px";
    s2.innerHTML = "共"+totalPages+"页 , "+totalNum+"条记录";
    div.appendChild(s2);


    // 上页链接
    if (page > 1) {
      var al2 = document.createElement("a");
      al2.setAttribute("href", "javascript:void(0);");
      al2.setAttribute("page", 1);
      new HsEventListener(al2, "click", _this.gotoPage);
      al2.innerHTML = " 最前页 ";
      div.appendChild(al2);
      var al = document.createElement("a");
      al.setAttribute("href", "javascript:void(0);");
      al.setAttribute("page", page - 1);
      new HsEventListener(al, "click", _this.gotoPage);
      al.innerHTML = "上一页";
      div.appendChild(al);
    }
    // 分页选择
    var s1 = document.createElement("span");
    s1.style.paddingLeft = "5px";
    s1.innerHTML = "转到第 ";
    div.appendChild(s1);
    var sel = document.createElement("select");
    for (i = 1; i <= totalPages; i ++) {
      var s = i.toString();
      sel.options.add(new Option(s, s));
      if (i == page) {
        sel.options[i-1].selected = true;
      }
    }
    new HsEventListener(sel, "change", _this.gotoPage);
    div.appendChild(sel);

    var s3 = document.createElement("span");
    s3.innerHTML = " 页";
    s3.style.paddingRight = "5px";
    div.appendChild(s3);

    // 下页链接
    if (page < totalPages) {
      var al = document.createElement("a");
      al.setAttribute("href", "javascript:void(0);");
      al.setAttribute("page", page + 1);
      new HsEventListener(al, "click", _this.gotoPage);
      al.innerHTML = "下一页";
      div.appendChild(al);
      var al2 = document.createElement("a");
      al2.setAttribute("href", "javascript:void(0);");
      al2.setAttribute("page", totalPages);
      new HsEventListener(al2, "click", _this.gotoPage);
      al2.innerHTML = " 最后页 ";
      div.appendChild(al2);
    }

    _this.listDiv.appendChild(div);
  };

  _this.makeCheck = function(checked) {
    var id = _this.info[_this.LA.idVar];
    var is_public = _this.info[_this.LA.publicVar];
    var nd = _this.LA.idsVar;
    var ck;

    if (HsBI.name == "MSIE") {
      checked = checked ? 'checked="checked"' : '';
      if(is_public == '0'){
         ck = document.createElement('<input type="checkbox" disabled name="'+nd+'" value="'+id+'" '+checked+'/>');
      }else{
         ck = document.createElement('<input type="checkbox" name="'+nd+'" value="'+id+'" '+checked+'/>');
      }
    }
    else {
      ck = document.createElement("input");
      ck.type = "checkbox";
      ck.name = nd;
      ck.value = id;
      ck.checked = checked ? true : false;
      if(is_public == '0'){
          ck.disabled = true;
      }
    }

    _this.td.appendChild(ck);
  };

  _this.makeFuncs = function() {
    var id = _this.info[_this.LA.idVar];
    var state = _this.info[_this.LA.stateVar];
    var is_public = _this.info[_this.LA.publicVar];
    if (_this.withFuncBtns["get"]) {
      var bt = hsMakeLink("查看", function(){_this.LA.get(id);});
      _this.td.appendChild(bt);
    }

    if (_this.withFuncBtns["set"]) {
      if(is_public == '0'){
          var bt = hsMakeLink("编辑", function(){},"list_disabled");
      }else{
          var bt = hsMakeLink("编辑", function(){_this.LA.set(id);},"list_edit");
      }
      _this.td.appendChild(bt);
    }

    if (_this.withFuncBtns["del"]) {
      if(is_public == '0'){
          var bt = hsMakeLink("删除", function(){}, "list_disabled");
      }else{
          var bt = hsMakeLink("删除", function(){_this.LA.del(id);}, "list_del");
      }
      _this.td.appendChild(bt);
    }
    if (_this.withFuncBtns["stop"]) {
      if(state == _this.stopVar){
        if(is_public == '0'){
          var bt = hsMakeLink("启用", function(){}, "list_disabled");
        }else{
          var bt = hsMakeLink("启用", function(){_this.start(id);}, "stop_ad");
        }
      }else{
        if(is_public == '0'){
          var bt = hsMakeLink("停用", function(){}, "list_disabled");
        }else{
          var bt = hsMakeLink("停用", function(){_this.stop(id);}, "stop_ad");
        }
      }
      _this.td.appendChild(bt);
    }
  };

  _this.checkAll = function(ev) {
    ev = hsGetStandardEvent(ev);
    _this.LA.checkAll(ev.target);
  };

  _this.gotoPage = function(page) {
    if (typeof page == "object" && page != null) {
      var ev = hsGetStandardEvent(page);
      if (ev.target.tagName == "SELECT") {
        page = hsGetSelectedOption(ev.target).value;
      }
      else {
        page = ev.target.getAttribute("page");
      }
    }
    page = page - 1;
    _this.setParams({"page":page});
    _this.loadList();
  };

  _this.gotoRowNum = function(rows) {
    if (typeof rows == "object" && rows != null) {
      var ev = hsGetStandardEvent(rows);
      if (ev.target.tagName == "SELECT") {
        rows = hsGetSelectedOption(ev.target).value;
      }
    }
    _this.setParams({"page_num":rows});
    _this.loadList();
  };
  _this.sortBy = function(sort, desc) {
    if (typeof sort == "object" && sort != null) {
      var ev = hsGetStandardEvent(sort);
      sort = ev.target.getAttribute("sort");
      desc = ev.target.getAttribute("desc");
    }
    _this.setParams({"sort":sort,"desc":desc});
    _this.loadList();
  };

  _this.find = function(text, vars) {
    if (typeof text == "object" && text != null) {
      var ev = hsGetStandardEvent(text);
         _this.setParams(ev.target.elements);
    }
    else {
      _this.setParams({find:text});
    }
    if (vars) {
      _this.setParams(vars);
    }
    _this.setParams({page:null});
    _this.loadList();
  };

  _this.listError = function(error, loading) {
    var ta = document.createElement("table");
    var tb = document.createElement("tbody");
    var tr = document.createElement("tr");
    var td = document.createElement("td");
    var txt = document.createTextNode(error);

    // 根据情况修改该设置
    td.align = "center";
    td.valign = "center";
    ta.cellpadding = "0";
    ta.cellspacing = "0";
    ta.style.width = "100%";
    if (loading == null){
      ta.className = "list_error";
    }
    else {
      ta.className = "list_loading";
    }

    td.appendChild(txt);
    tr.appendChild(td);
    tb.appendChild(tr);
    ta.appendChild(tb);
    _this.listDiv.innerHTML = "";
    _this.listDiv.appendChild(ta);
  };

  
  
  
  _this.getArrValue = function(arr, key) {
    var value = arr;
    var keys = key.split(".");
    for (var i = 0; i < keys.length; i ++) { 
      try{
    	  value = value[keys[i]];
      }catch(e){}
    }
    return value;
  };

  _this.getWindow = function(w) {
    if (!_this.W) {
      _this.setWindow();
    }
    return _this.W;
  };

  _this.setWindow = function(w) {
    if (!w) {
      w = window;
    }
    _this.W = w;
  };

  /** 伪事件 **/

  // 操作完成(返回False阻止默认行为)
  _this.onBack = function() {
    return false;
  };

  // 操作失败
  _this.onFail = function() {
  };

  // 加载完成
  _this.onLoad = function(rst) {
  };

  /** AFA附加操作 **/

  _this.stop = function(id, isStart) {
    var send = [];
    self.stopIds = [];
    if (typeof id == "string") {
      send.push({name:_this.LA.idsVar,value:id});
      stopIds.push(id);
    }
    else {
      var a = hsName(_this.LA.idsVar);
      for (var i = 0; i < a.length; i ++) {
        if (a[i].checked) {
          send.push({name:_this.LA.idsVar,value:a[i].value});
          stopIds.push(a[i].value);
        }
      }
      if (send.length == 0) {
        if (isStart === true) {
          alert("请选择要开启的数据行");
        }
        else {
          alert("请选择要停用的数据行");
        }
        return false;
      }
    }
    send.push({name:"type",value:isStart === true ? _this.startVar : _this.stopVar});
    if(isStart !== true && _this.stopBackFunc){
        new HsAjaxRequest(_this.stopBackFunc, "POST", _this.stopAction, send);
    }else{
        if (!confirm('是否确定要更改数据状态?')) {
          return false;
        }
        _this.LA.actionSubmit(_this.stopAction,send);
        //var rsp = hsAjaxRequestPost(_this.stopAction, send);
        //var rst = hsAjaxRequestResult(rsp);
    }
    return false;
  };

  _this.start = function(id) {
    _this.stop(id, true);
  };
}

/** 表单加载器 **/

function HsFormLoader(formObj) {
  var _this = this;

  if (typeof formObj == "string") {
    _this.formObj = hsId(formObj);
  }
  else {
    _this.formObj = formObj;
  }

  _this.fields = {};
  _this.checker = {};
  _this.checked = {};

  _this.FA = new HsFormAction();
  _this.FA.useFW = true;

  self.FA = _this.FA;

  _this.setAttributes = function(attrib) {
    _this.loadAction = attrib.loadAction;
    _this.noIdNoLoad = attrib.noIdNoLoad ? true : false;
  };

  _this.setFields = function(fields) {
    _this.fields = fields;
  };

  _this.setChecker = function(checker) {
    _this.checker = checker;
  };

  _this.loadInfo = function() {
    var rsp, rst;
    var url = _this.loadAction;
    var arr = location.href.match(/[\?&]id=([^&#]*)/);
    if (arr) {
      _this.formObj.elements["id"].value = arr[1];
      url = hsUrlBindParam(url, "id", arr[1]);

      // 加载数据
      rsp = hsAjaxRequestGet(url);
      rst = hsAjaxRequestResult(rsp, 3);
    }
    else if (!_this.noIdNoLoad) {
      // 加载数据
      rsp = hsAjaxRequestGet(url);
      rst = hsAjaxRequestResult(rsp, 3);
    }
    else {
      // 虚构数据
      rst = {__result:true};
    }
    // 加载失败
    if (rst == null) {
      _this.fromError("加载数据失败");
      return;
    }
    if (!rst.__result) {
      if (!rst.__message) {
        _this.formError("加载数据失败");
      }
      else {
        _this.formError(rst.__message);
      }
      return;
    }

    // 清空信息
    _this.formError();

    _this.onLoad(rst);
    // 设置数据及信息
    if (rst.data) {
      _this.setData(rst.data);
    }
    if (rst.info) {
      _this.setInfo(rst.info);
    }

    _this.FA.formObj = _this.formObj;
    _this.FA.init();
    _this.FA.checkAction(_this.checker);

    delete _this.fields;
    delete _this.checker;
  };

  _this.setData = function(data) {
    for (var field in _this.fields) {
      var conf = _this.fields[field];
      var value = data[field];

      if (typeof value == "undefined") {
        continue;
      }

      var input = _this.formObj.elements[field];
      if (input == null) {
        if (conf.type == "radio" || conf.type == "check" || conf.type == "select") {
          input = {};
        }
        else {
          continue;
        }
      }

      _this.field = field;
      _this.input = input;

      if (conf.dataFunc) {
        value = conf.dataFunc(value, _this);
      }
      if (value == null) {
        continue;
      }

      if (conf.type == "select" || input.tagName == "SELECT") {
        if (conf.type == "select") {
          input = document.createElement("select");
          input.name = field;
          hsId(field+"_box").appendChild(input);

          // 加入到form对象的elemnts中(IE BUG)
          if (HsBI.name == "MSIE") {
            _this.formObj.elements[field] = input;
          }
        }

        var t, v;
        t = conf.text  ? conf.text  : "text"  ;
        v = conf.value ? conf.value : "value" ;

        if (typeof value.length != "number") {
          value = hsObjectValues(value);
        }

        for (var i = 0; i < value.length; i ++) {
          var opt = new Option(value[i][t], value[i][v]);

          delete value[i][t];
          delete value[i][v];

          for (var k in value[i]) {
            opt.setAttribute(k, value[i][k]);
          }

          input.options.add(opt);
        }
      }
      else if (conf.type == "check") {
        var t, v;
        t = conf.text  ? conf.text  : "text"  ;
        v = conf.value ? conf.value : "value" ;

        if (typeof value.length != "number") {
          value = hsObjectValues(value);
        }

        var chks = [];

        var box = hsId(field+"_box");
        for (var i = 0; i < value.length; i ++) {
          var lab = document.createElement("label");
          var chk = document.createElement("input");
          var txt = document.createTextNode(value[i][t]+" ");

          chk.type = "checkbox"
          chk.name = field;
          chk.value = value[i][v];
          chk.checked = false;

          lab.appendChild(chk);
          lab.appendChild(txt);
          box.appendChild(lab);

          delete value[i][t];
          delete value[i][v];

          for (var k in value[i]) {
            chk.setAttribute(k, value[i][k]);
          }

          chks.push(chk);
        }

        // 加入到form对象的elemnts中(IE6 BUG)
        if (HsBI.name == "MSIE") {
          _this.formObj.elements[field] = chks;
        }
      }
      else if (conf.type == "radio") {
        var t, v;
        t = conf.text  ? conf.text  : "text"  ;
        v = conf.value ? conf.value : "value" ;

        if (typeof value.length != "number") {
          value = hsObjectValues(value);
        }

        var rads = [];

        var box = hsId(field+"_box");
        for (var i = 0; i < value.length; i ++) {
          var lab = document.createElement("label");
          var rad = document.createElement("input");
          var txt = document.createTextNode(value[i][t]+" ");

          rad.type = "radio";
          rad.name = field;
          rad.value = value[i][v];
          rad.checked = false;

          lab.appendChild(rad);
          lab.appendChild(txt);
          box.appendChild(lab);

          delete value[i][t];
          delete value[i][v];

          for (var k in value[i]) {
            rad.setAttribute(k, value[i][k]);
          }

          rads.push(rad);

          // 自定义选择方法(IE6/7 BUG)
          if (HsBI.name == "MSIE" && HsBI.version < 8) {
            new HsEventListener(
              rad, "click",
              function(ev) {
                var rad = ev.target;
                var key = ev.target.name;
                if (_this.checked[key] && _this.checked[key] != rad) {
                  _this.checked[key].checked = false;
                }
                _this.checked[key] = rad;
                rad.checked = true;
              }
            );
          }
        }

        // 加入到form对象的elements中(IE6/7 BUG)
        if (HsBI.name == "MSIE" && HsBI.version < 8) {
          _this.formObj.elements[field] = rads;
        }
      }
      else {
        for (var k in value) {
          input.setAttribute(k, value[k]);
        }
      }
    }

    delete _this.field;
    delete _this.input;
  };

  _this.setInfo = function(info) {
    for (var field in _this.fields) {
      var conf = _this.fields[field];
      var value = info[field];

      var input = _this.formObj.elements[field];
      if (input == null) {
        continue;
      }

      if (input.type == 'radio' || input.type == 'checkbox') {
        input = [input];
      }
      if (input.type == undefined && input.length != undefined) {
        input.type = input[0].type;
      }

      _this.field = field;
      _this.input = input;

      if (conf.infoFunc) {
        value = conf.infoFunc(value, _this);
      }
      if (value == null) {
        continue;
      }

      if (input.tagName == "SELECT") {
        hsSelectOption(input, value);
      }
      else if (input.type == "radio") {
        for (var i = 0; i < input.length; i ++) {
          input[i].checked = false;
          if (input[i].value == value) {
            input[i].checked = true;
            break;
          }
        }
      }
      else if (input.type == "checkbox") {
        for (var i = 0; i < input.length; i ++) {
          input[i].checked = false;
          for (var j = 0; j < info[field].length; j ++) {
            if (input[i].value == value) {
              input[i].checked = true;
              break;
            }
          }
        }
      }
      else {
        input.value = value;
      }
    }

    delete _this.field;
    delete _this.input;
  };

  _this.formError = function(error) {
    var div = hsId(_this.formObj.name+"_err");
    if (div) {
      if (error) {
        div.style.display = "";
        div.innerHTML = error;
      }
      else {
        div.style.display = "none";
      }
    }
  };

  _this.onLoad = function(rst) {
  };
  _this.onFail = function(rst) {
  };
};

/** 其他 **/

function hsMakeLink(text, func, className) {
  var a = document.createElement("a");
  a.setAttribute("href", "javascript:void(0)");
  a.appendChild(document.createTextNode(text));
  if (func) {
    new HsEventListener(a, "click", func);
    a.className = className;
  }
  else {
    a.className = "list_dis";
  }
  return a;
}

function hsMakeButton(text, func, className) {
  var b = document.createElement("input");
  b.type = "button";
  b.value = text;
  if (func) {
    new HsEventListener(b, "click", func);
    b.className = className;
  }
  else {
    b.disabled = true;
  }
  return b;
}
function hsMakeText(text, func, className) {
	  var c = document.createElement("span");
	  c.setAttribute('style','padding-left:40px');
	  c.appendChild(document.createTextNode(text));
	  if (func) {
	    new HsEventListener(c, "click", func);
	    c.className = className;
	  }
	  else {
	    c.className = "list_dis";
	  }
	  return c;
	}
